#include "ContextMenuManager.h"
#include "gen2/SemanticModel.h"
#include <QtGui>
#include "StringTools.h"

ContextMenuManager ContextMenuManager::_instance;

ContextMenuManager::ContextMenuManager(void)
{
	_deleteAction = 0;
}

ContextMenuManager::~ContextMenuManager(void)
{
	for (iterator menu = begin(); menu != end(); ++menu)
		delete *menu;
	if (_deleteAction)
		delete _deleteAction;
}
	
QMenu& ContextMenuManager::get(ContextMenuTarget targetType)
{
	const_iterator i = find(targetType);
	if (i == end())
	{
		QMenu* menu = createContextMenu(targetType);
		i = insert(targetType, menu);
	}
	return **i;	
}


template<int N>
void fillRelationsMenu(QMenu* menu, const SemanticModel::RelationType (*relations)[N])
{
	int count = N;
	for (const SemanticModel::RelationType* i = *relations; i != *relations + count; ++i)
	{
		QString name = toQString(SemanticModel::Relation::nameOf(*i));
		QAction* action = menu->addAction(QIcon(":/images/relation.png"), name);
		action->setData(*i);
	}
}

QAction* ContextMenuManager::deleteAction()
{
	if (!_deleteAction)
		_deleteAction = new QAction(QIcon(":/images/delete.png"),			
			QObject::tr("Delete"), 0);
	return _deleteAction;
}

QMenu* ContextMenuManager::createContextMenu(ContextMenuTarget targetType)
{
	QMenu* menu = new QMenu();
	if ((targetType & RelationMenu) == RelationMenu)
	{
		switch (targetType & (ToClassMenu | FromClassMenu))
		{
			case ToClassMenu | FromClassMenu:
				fillRelationsMenu(menu, &SemanticModel::ClassClassRelations);
				break;
			case FromClassMenu:
				fillRelationsMenu(menu, &SemanticModel::ClassOperationRelations);
				break;
			case ToClassMenu:
				fillRelationsMenu(menu, &SemanticModel::OperationClassRelations);
				break;
			case 0:				
				fillRelationsMenu(menu, &SemanticModel::OperationOperationRelations);
				break;
		}
		menu->addSeparator();
	}
	else if ((targetType & ClassMenu) == ClassMenu)
	{
		// ...
	}
	menu->addAction(deleteAction());
	return menu;
}
